from invenio.bibconvert_python_engine import Record, Field, Controlfield, Subfield
from invenio.bibtask import task_low_level_submission
from invenio.config import CFG_TMPDIR
import os
import time

def Finish_Reindex(parameters, curdir, form, user_info=None):
	rec = Record()
	recid = open(os.path.join(curdir, "SN")).read()
	rec.add_field(Controlfield("001", recid))
	for subject in open(os.path.join(curdir, "selectedSubjects"), "r"):
		if subject.strip != "":
			sf = Field("650", ind2="7")
			sf.add_subfield(Subfield("a", subject.strip()))
			sf.add_subfield(Subfield("2", "PSH"))
			rec.add_field(sf)
			
	for subject in open(os.path.join(curdir, "otherSubjects"), "r"):
		if subject.strip != "":
			parts = subject.split("---")
			sf = Field("650", ind2="7")
			sf.add_subfield(Subfield("a", parts[0].strip()))
			sf.add_subfield(Subfield("2", parts[1].strip()))
			rec.add_field(sf)
	output_file_path = os.path.join(CFG_TMPDIR, "reindex_nusl-%s_%s" % (recid, time.strftime("%Y-%m-%d_%H:%M:%S")))
	output_file = open(output_file_path, "w")
	output_file.write(rec.to_xml())
	task_low_level_submission("bibupload", "reindex", "-c", output_file_path)
	
	